{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  9           0 LOAD_FAST                0 (a)\n",
      "              2 LOAD_CONST               1 (1)\n",
      "              4 BINARY_ADD\n",
      "              6 STORE_FAST               0 (a)\n",
      "\n",
      " 10           8 LOAD_FAST                0 (a)\n",
      "             10 RETURN_VALUE\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "## gil\n",
    "## 全局解释器锁 Global Interpreter Lock\n",
    "\n",
    "## python 中一个线程对应于C语言的一个线程\n",
    "## gil 使得同一个时刻只有一个线程在一个cpu上执行\n",
    "\n",
    "import dis\n",
    "def add(a):\n",
    "    a = a + 1\n",
    "    return a\n",
    "\n",
    "print(dis.dis(add))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-200068\n"
     ]
    }
   ],
   "source": [
    "## GIL \n",
    "## 会根据执行的字节码行数以及时间片释放GIL\n",
    "## 在遇到io操作的时候主动释放\n",
    "\n",
    "import threading\n",
    "\n",
    "total = 0\n",
    "\n",
    "def add():\n",
    "    global total\n",
    "    for i in range(1000000):\n",
    "        total += 1\n",
    "        \n",
    "def desc():\n",
    "    global total\n",
    "    for i in range(1000000):\n",
    "        total -= 1\n",
    "\n",
    "thread1 = threading.Thread(target=add)\n",
    "thread2 = threading.Thread(target=desc)\n",
    "thread1.start()\n",
    "thread2.start()\n",
    "\n",
    "thread1.join()\n",
    "thread2.join()\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
